<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" />
    <BasicTable @register="registerTable" class="w-3/4 xl:w-4/5" @fetch-success="tableFetchSuccess">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate" v-auth="'UserManagerPriv.Add'"
          >新增账号</a-button
        >
        <a-button
          v-auth="'UserManagerPriv.Enable'"
          :loading="loadingEnabled"
          type="primary"
          @click="handleEnableBatch"
          :disabled="getRowSelection().selectedRowKeys.length == 0"
          >启用</a-button
        >
        <a-button
          v-auth="'UserManagerPriv.Disable'"
          :loading="loadingDisabled"
          type="primary"
          @click="handleDisabledBatch"
          :disabled="getRowSelection().selectedRowKeys.length == 0"
          >禁用</a-button
        >
        <a-button
          v-auth="'UserManagerPriv.Delete'"
          :loading="loadingDel"
          color="error"
          @click="handleDeleteBatch"
          :disabled="getRowSelection().selectedRowKeys.length == 0"
          >删除</a-button
        >
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              auth: 'UserManagerPriv.PrivRange',
              icon: 'ion:git-compare-outline',
              onClick: handlePermission.bind(null, record),
            },
            {
              auth: 'UserManagerPriv.Edit',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
            },
          ]"
          :dropDownActions="[
            {
              auth: 'UserManagerPriv.Delete',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
            {
              auth: 'UserManagerPriv.ChangePassword',
              label: '修改密码',
              onClick: handleModifyPassword.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <UserModal @register="registerModal" @success="handleSuccess" />
    <MenuPermissionModal @register="permissionRegisterModel" />
    <ModifyPasswordModal @register="modifyPassRegisterModal" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getUserListByPage,
    setUserStatus,
    deleteUser,
    getRoleListByBranch,
  } from '/@/api/system/system';
  import { PageWrapper } from '/@/components/Page';
  import DeptTree from './DeptTree.vue';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import UserModal from './UserModal.vue';
  import MenuPermissionModal from '../components/MenuPermissionModal.vue';
  import ModifyPasswordModal from './ModifyPasswordModal.vue';

  import { columns, searchFormSchema } from './user.data';

  export default defineComponent({
    name: 'UserManager',
    components: {
      BasicTable,
      PageWrapper,
      DeptTree,
      UserModal,
      TableAction,
      MenuPermissionModal,
      ModifyPasswordModal,
    },
    setup() {
      const { createMessage, createConfirm } = useMessage();
      let loadingEnabled = ref(false);
      let loadingDisabled = ref(false);
      let loadingDel = ref(false);
      const [registerModal, { openModal }] = useModal();
      const [
        registerTable,
        { reload, getSelectRowKeys, clearSelectedRowKeys, getRowSelection, getForm },
      ] = useTable({
        title: '账号列表',
        api: getUserListByPage,
        beforeFetch: (parmas) => {
          if (parmas.roles) {
            parmas.roles = parmas.roles.join();
          }
        },
        rowKey: 'userName',
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        rowSelection: {
          type: 'checkbox',
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable) {
        await deleteUser(record.userName);
        reload();
        createMessage.success('删除成功');
      }

      async function handleEnableBatch() {
        loadingEnabled.value = true;
        await setUserStatus(getSelectRowKeys().join(), true);
        reload();
        loadingEnabled.value = false;
        createMessage.success('操作成功');
      }

      async function handleDisabledBatch() {
        loadingDisabled.value = true;
        await setUserStatus(getSelectRowKeys().join(), false);
        clearSelectedRowKeys();
        reload();
        loadingDisabled.value = false;
        createMessage.success('操作成功');
      }

      async function handleDeleteBatch() {
        createConfirm({
          iconType: 'warning',
          title: '确定要删除吗？删除后无法恢复！',
          okType: 'danger',
          async onOk() {
            loadingDel.value = true;
            await deleteUser(getSelectRowKeys().join());
            clearSelectedRowKeys();
            reload();
            loadingDel.value = false;
          },
        });
      }

      function handleSuccess() {
        reload();
      }

      function handleSelect(branchInnercode = '') {
        reload({ searchInfo: { branchInnercode } });
        resetRoleOptions(branchInnercode);
      }

      nextTick(() => {
        resetRoleOptions('');
      });

      function tableFetchSuccess() {}

      function resetRoleOptions(branchInnercode) {
        getRoleListByBranch({ branchInnercode }).then((roleList) => {
          let data: any = [];
          roleList.forEach((val) => {
            data.push({ value: val.roleCode, label: val.roleName });
          });
          getForm().updateSchema({
            field: 'roles',
            componentProps: {
              mode: 'multiple',
              options: data,
            },
          });
        });
      }

      /***************************权限范围Modal***********************************/

      const [permissionRegisterModel, permissionModalMethods] = useModal();

      function handlePermission(record: Recordable) {
        permissionModalMethods.openModal(true, { id: record.userName, type: 'U' });
      }

      /***************************修改密码Modal***********************************/
      const [modifyPassRegisterModal, modifyPassModalMethods] = useModal();

      function handleModifyPassword(record: Recordable) {
        modifyPassModalMethods.openModal(true, { record });
      }

      return {
        registerTable,
        registerModal,
        tableFetchSuccess,
        getSelectRowKeys,
        getRowSelection,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        permissionRegisterModel,
        handlePermission,
        handleModifyPassword,
        handleEnableBatch,
        handleDisabledBatch,
        handleDeleteBatch,
        modifyPassRegisterModal,
        loadingEnabled,
        loadingDisabled,
        loadingDel,
      };
    },
  });
</script>
